<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background: url(https://img.zcool.cn/community/01714a5c5901b1a801203d223f67e1.jpg@1280w_1l_2o_100sh.jpg) no-repeat;
            background-size: cover;
            height: 100vh;
        }

        #canvas {
            margin: auto;
            display: block;
            box-shadow: 0 5px 5px rgba(0, 0, 0, .5);
            background: whitesmoke;
        }
    </style>
</head>

<body>

    <canvas id="canvas"></canvas>

    <script>
        var canvas = document.querySelector("#canvas");
        var WIDTH = 500,
            HEIGHT = 700;

        canvas.width = WIDTH;
        canvas.height = HEIGHT;

        var x = 0;
        var y = 0;
        var boxGo = true; // ture向右
        var boxGoup = true;

        var ctx = canvas.getContext('2d');

        var timer = setInterval(function () {

            ctx.fillStyle = '#fff';
            ctx.fillRect(0, 0, WIDTH, HEIGHT);
            ctx.fillStyle = 'yellowgreen';
            ctx.fillRect(x, y, 50, 50);

            if (boxGo) {
                x += 5;
            } else {
                x -= 5;
            }
            if (boxGoup) {
                y += 5;
            } else {
                y -= 5;
            }
            if (x >= WIDTH - 50) {
                boxGo = false;
            }
            if (x <= 0) {
                boxGo = true;
            }
            if (y >= HEIGHT - 50) {
                boxGoup = false;
            }
            if (y <= 0) {
                boxGoup = true;
            }
        }, 1000 / 60);
    </script>

</body>

</html>